package avicit.cbb.techclass.tabledefine.commtempletmanager.action;

import avicit.cbb.appreg.service.CommSysInfoIntfsService;
import avicit.cbb.techclass.appreg.domain.CbbSysInfo;
import avicit.cbb.techclass.appreg.service.CommSysInfoService;
import avicit.cbb.techclass.tabledefine.commtablemanager.domain.CbbTabColumns;
import avicit.cbb.techclass.tabledefine.commtablemanager.action.service.CommTableManagerService;
import avicit.cbb.techclass.tabledefine.commtablemanager.action.service.api.CommTableManagerServiceApi;
import avicit.cbb.techclass.tabledefine.commtempletmanager.action.service.api.CommTempletManagerServiceApi;
import avicit.cbb.techclass.tabledefine.commtempletmanager.domain.CbbTempletCode;
import avicit.cbb.techclass.tabledefine.commtempletmanager.domain.CbbTempletField;
import avicit.cbb.techclass.tabledefine.commtempletmanager.domain.CbbTempletInfo;
import avicit.cbb.techclass.tabledefine.commtempletmanager.rest.CommTempletManagerService;
import avicit.cbb.techclass.tabledefine.commtempletmanager.rest.api.CommTempletManagerService;
import avicit.filebasicmanager.api.CommSysInfoServiceApi;
import avicit.filebasicmanager.api.CommTempletManagerServiceApi;
import avicit.platform6.api.session.SessionHelper;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.JsonHelper;
import avicit.platform6.commons.utils.JsonUtils;
import avicit.platform6.commons.utils.Pinyin4jUtil;
import avicit.platform6.commons.utils.RequestUtil;
import avicit.platform6.commons.utils.web.TreeNode;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.dao.Paging;
import avicit.platform6.core.jdbc.Page;
import avicit.platform6.core.properties.PlatformConstant.OpResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;

/**
 * 参考模版Controller 创建时间 ：2014-08-19
 *
 * @author 朱锋
 */

@Controller
@RequestMapping("/aos/commtempletmanagerController")
@Scope("prototype")
@SuppressWarnings({"unchecked","deprecation"})
public class CommTempletManagerController {

	private static final Logger logger = LoggerFactory.getLogger(CommTempletManagerController.class);

	@Autowired
	private CommTableManagerServiceApi commTableManagerService;
	@Autowired
	private CommTempletManagerServiceApi commTempletManagerService;
	@Autowired
	private CommSysInfoService commSysInfoService;
	@Autowired
	CommSysInfoIntfsService commSysInfoIntfsService;

	/**
	 * 获取参考模板基本信息
	 *
	 * @author 朱锋
	 * @param response
	 * @param request
	 * @return ModelAndView
	 * @throws Exception
	 *             ModelAndView
	 */
	@RequestMapping(value = "/getCommTempletInfoData")
	@ResponseBody
	public Map<String,Object> getCommTempletInfoData(HttpServletResponse response, HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String json = ServletRequestUtils.getStringParameter(request,"param","");
		String tempCode = ServletRequestUtils.getStringParameter(request,"code");
		String tempName = ServletRequestUtils.getStringParameter(request,"name");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		Map<String, Object> parameter = new HashMap<String, Object>();
		if (json != null && !"".equals(json)) {
			parameter = JsonHelper.getInstance().readValue(json, Map.class);
		}

		parameter.put("filter_LIKE_tempCode", tempCode);
		parameter.put("filter_LIKE_tempName", tempName);
		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量

		Paging<CbbTempletInfo> page = new Paging<CbbTempletInfo>();
		page.setPageSize(ComUtil.getPageSize(pageSize));
		page.setPageNo(ComUtil.getPageNo(pageNo));
		page = commTempletManagerService.getPageList(page, parameter, sysId);
		map.put("total", page.getTotalCount());
		map.put("rows", page.getResult());
		return map;
	}

	/**
	 * 跳转参考模板基本信息添加页面
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/toCommTempletAdd")
	public ModelAndView toAuthorizeJsp(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		String dialogId = ServletRequestUtils.getStringParameter(request,"dialogId","");
		String pid = ServletRequestUtils.getStringParameter(request,"pid","");
		String type = ServletRequestUtils.getStringParameter(request,"type","");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");// 系统标识
		mav.addObject("dialogId", dialogId);
		mav.addObject("pid", pid);
		mav.addObject("type", type);
		mav.addObject("sysId", sysId);
		// 根据系统标识表ID获取系统标识名称
		if (sysId != null && !"O".equals(sysId)) {
			mav.addObject("sysName", "LANTOP");
		}
		// 获取系统标识数据
//		List<CbbSysInfo> commSysInfoList = commTempletManagerService.getCommSysInfo(ThreadContextHelper.getOrgId());
//		mav.addObject("commSysInfoList", commSysInfoList);
		mav.setViewName("avicit/cbb/techclass/tabledefine/commtempletmanager/comm_templet_add");
		return mav;
	}

	/**
	 * 获取参考模板基本信息编辑页面所需要的值
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toCommTempletEdit")
	public ModelAndView toEditJsp(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		String id = ServletRequestUtils.getStringParameter(request,"id","");
		String dialogId = ServletRequestUtils.getStringParameter(request,"dialogId","");
		String toJspUrl = ServletRequestUtils.getStringParameter(request,"toJspUrl","");
		CbbTempletInfo commTempletInfo = commTempletManagerService.getCommTempletInfoById(id);
		mav.addObject("commTempletInfo", commTempletInfo);
		mav.addObject("dialogId", dialogId);
		// 获取系统标识
//		CbbSysInfo commSysInfo = commTempletManagerService.getCommSysInfoById(commTempletInfo.getSysId());
//		mav.addObject("sysId", commSysInfo.getSysName());
		mav.setViewName(toJspUrl);
		return mav;
	}

	/**
	 * 参考模板基本信息名称唯一性验证
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/checkUnique")
	@ResponseBody
	public Map<String,Object> checkCodeAndNameUnique(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String json = ServletRequestUtils.getStringParameter(request,"param","");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		CbbTempletInfo commTempletInfo = JsonHelper.getInstance().readValue(json, CbbTempletInfo.class);
		try {
			// 唯一性验证【名称唯一性验证】
			boolean codeUnique = false;
			String name = commTempletInfo.getTempName();
			String id = commTempletInfo.getId();
			codeUnique = commTempletManagerService.checkUnique(name, id, sysId);
			if (codeUnique) {
				map.put("flag", "名称<font color='blue'>[" + name + "]</font>已存在,请重新填写!");
			} else {
				map.put("flag", OpResult.success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("flag", OpResult.failure);
		}
		return map;
	}

	/**
	 * 手写通用代码显示值，真实值唯一性验证
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/checkCodeUnique")
	@ResponseBody
	public Map<String,Object> checkCodeUnique(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String json = request.getParameter("param");
		String sysId = request.getParameter("sysId");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		CbbTempletCode commTempletCode = JsonHelper.getInstance().readValue(json, CbbTempletCode.class);
		try {
			// 唯一性验证【名称唯一性验证】
			int codeUnique = 0;
			String id = commTempletCode.getId();
			String tid = commTempletCode.getTempletId();
			String fid = commTempletCode.getFieldId();
			String lookupName = commTempletCode.getLookupName();
			String lookupCode = commTempletCode.getLookupCode();
			codeUnique = commTempletManagerService.checkCodeUnique(lookupName, lookupCode, id, tid, fid, sysId);
			if (codeUnique == 1) {
				map.put("flag", "显示值<font color='blue'>[" + lookupName + "]</font>已存在,请重新填写!");
			}
			if (codeUnique == 2) {
				map.put("flag", "真实值 <font color='blue'>[" + lookupCode + "]</font>已存在,请重新填写!");
			}
			if (codeUnique == 3) {
				map.put("flag", OpResult.success);
			}
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}

		return map;
	}

	/**
	 * 参考模板基本信息保存方法
	 *
	 * @param request
	 *            请求参数
	 * @return
	 */
	@RequestMapping("/insertOrUpdateCommTempletInfoData")
	@ResponseBody
	public Map<String,Object> doSave(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String json = request.getParameter("param");
		CbbTempletInfo commTempletInfo = JsonHelper.getInstance().readValue(json, CbbTempletInfo.class);
		boolean isUpdate = StringUtils.isBlank(commTempletInfo.getId()) ? false : true;
		try {
			if (isUpdate) {
				commTempletManagerService.updateCommTempletInfo(commTempletInfo);
			} else {
				if (!commTempletInfo.getTempType().equals("C")) {
					commTempletInfo.setTempModelType("");
				}
				commTempletManagerService.insertCommTempletInfo(commTempletInfo, ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId());
			}
			map.put("flag", OpResult.success);
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}
		return map;
	}

	/**
	 * 系统通用代码导入方法
	 *
	 * @param request
	 *            请求参数
	 * @return
	 */
	@RequestMapping("/insertSysCodeData")
	@ResponseBody
	public Map<String,Object> insertSysCodeData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String cid = ServletRequestUtils.getStringParameter(request,"cid","");
		String tid = ServletRequestUtils.getStringParameter(request,"tid","");
		String fid = ServletRequestUtils.getStringParameter(request,"fid","");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		try {
			commTempletManagerService.insertSysCode(cid, tid, fid, sysId, ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId());
			map.put("flag", OpResult.success);
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}

		return map;
	}

	/**
	 * 删除参考模板基本信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/deleteCommTempletInfo")
	@ResponseBody
	public Map<String,Object> deleteCommTempletInfo(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<>();
		try {
			String id = ServletRequestUtils.getStringParameter(request,"id","");
			String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
			if ("".equals(sysId) || sysId == null) {
				sysId = "CBB";
			}
			sysId = "LANTOP";
			if (id != null && !"".equals(id)) {
				commTempletManagerService.deleteCommTempletInfoById(id, sysId);
				map.put("flag", OpResult.success);
			}
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}

		return map;
	}

	/**
	 * 获取参考模板字段信息
	 *
	 * @author 朱锋
	 * @param response
	 * @param request
	 * @return ModelAndView
	 * @throws Exception
	 *             ModelAndView
	 */
	@RequestMapping(value = "/getCommTempletFieldData")
	@ResponseBody
	public Map<String,Object> getCommTempletFieldData(HttpServletResponse response, HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String isStructure = ServletRequestUtils.getStringParameter(request,"isStructure","");// N：参考模板树，Y：库结构树
		String json = ServletRequestUtils.getStringParameter(request,"param","");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		String isTemplet = ServletRequestUtils.getStringParameter(request,"isTemplet","");
		String tid = ServletRequestUtils.getStringParameter(request,"tid","");
		String colName = ServletRequestUtils.getStringParameter(request,"colName","");
		String colLabel = ServletRequestUtils.getStringParameter(request,"colLabel","");
		if ("".equals(tid) || null == tid) {
			tid = commTempletManagerService.getTempltIdByTempltCode(sysId + "_TEMPLATE", sysId);
		}
		if (!"".equals(colName) && colName != null) {
			colName = URLDecoder.decode(colName, "utf-8");// 编码转换
		}
		if (!"".equals(colLabel) && colLabel != null) {
			colLabel = URLDecoder.decode(colLabel, "utf-8");// 编码转换
		}

		// 参考模板树类型
		String treeType = ServletRequestUtils.getStringParameter(request,"treeType","");
		String orgId = ThreadContextHelper.getOrgId();
		if (null != treeType && treeType.equals("root")) {// 为根组织树
			orgId = "ORG_ROOT";// 设为根组织ID
		}

		String tableName = ServletRequestUtils.getStringParameter(request,"tableName","");
		if ("Y".equals(isStructure)) {
			// 库结构树获取表数据
			// 查询tableId
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("orgId", orgId);
			String tableId = commTableManagerService.getTableIdBysysIdAndTableName(sysId, tableName, param);
			if (tableId.equals("")) {
				tableId = "@@@";
			}
			Map<String, Object> parameter = new HashMap<String, Object>();
			if (json != null && !"".equals(json)) {

				parameter = JsonHelper.getInstance().readValue(json, Map.class);
			}

			parameter.put("tableId", tableId);
			parameter.put("isTemplet", isTemplet);
			String pageNo = request.getParameter("page");// 取得当前页码
			String pageSize = request.getParameter("rows");// 取得一页显示的数量
			Paging<CbbTabColumns> page = new Paging<CbbTabColumns>();
			page.setPageSize(ComUtil.getPageSize(pageSize));
			page.setPageNo(ComUtil.getPageNo(pageNo));
			Map<String, Object> map1 = commTableManagerService.getPageDetailList(page, parameter, sysId);
			int count = Integer.valueOf(String.valueOf(map1.get("count")));
			// 由于修改时JSON串传出的以下两个属性为毫秒数,无法映射到对象里,所以此时把这两个置为空
			List<CbbTabColumns> list = (List<CbbTabColumns>) map1.get("list");
			for (CbbTabColumns cbbTabColumns : list) {
				cbbTabColumns.setCreationDate(null);
				cbbTabColumns.setLastUpdateDate(null);
			}
			map1.put("total", count);
			map1.put("rows", list);
		} else {
			// 参考模板树获取表数据
			// SanXiaFiles Create By Tangkun Start
			String inputWord = request.getParameter("inputWord");
			if (inputWord != null && !"".equals(inputWord)) {
				colLabel = URLDecoder.decode(inputWord, "utf-8");
			}
			// SanXiaFiles Create By Tangkun End
			Map<String, Object> parameter = new HashMap<String, Object>();
			if (json != null && !"".equals(json)) {
				parameter = JsonHelper.getInstance().readValue(json, Map.class);
			}
			parameter.put("filter_LIKE_colName", colName);
			parameter.put("filter_LIKE_colLabel", colLabel);
			parameter.put("filter_LIKE_templetId", tid);
			parameter.put("filter_EQ_orgId", orgId);
			String pageNo = request.getParameter("page");// 取得当前页码
			String pageSize = request.getParameter("rows");// 取得一页显示的数量
			Paging<CbbTempletField> page = new Paging<CbbTempletField>();
			page.setPageSize(ComUtil.getPageSize(pageSize));
			page.setPageNo(ComUtil.getPageNo(pageNo));
			page = commTempletManagerService.getPageDetailList(page, parameter, sysId);
			// 由于修改时JSON串传出的以下两个属性为毫秒数,无法映射到对象里,所以此时把这两个置为空
			List<CbbTempletField> list = page.getResult();
			for (CbbTempletField cbbTempletField : list) {
				cbbTempletField.setCreationDate(null);
				cbbTempletField.setLastUpdateDate(null);
			}
			map.put("total", page.getTotalCount());
			map.put("rows", page.getResult());
		}
		return map;
	}

	/**
	 * 获取通用代码信息
	 *
	 * @author 朱锋
	 * @param response
	 * @param request
	 * @return ModelAndView
	 * @throws Exception
	 *             ModelAndView
	 */
	@RequestMapping(value = "/getCommTempletCodeData")
	@ResponseBody
	public Map<String,Object> getCommTempletCodeData(HttpServletResponse response, HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String fid = ServletRequestUtils.getStringParameter(request,"fid","");
		String tid = ServletRequestUtils.getStringParameter(request,"tid");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("tid", tid);
		parameter.put("fid", fid);
		Paging<CbbTempletCode> page = new Paging<CbbTempletCode>();
		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		page.setPageSize(ComUtil.getPageSize(pageSize));
		page.setPageNo(ComUtil.getPageNo(pageNo));
		Page<Map<String, Object>> result = commTempletManagerService.getPageCodeDetailList(page, parameter, sysId);
		map.put("total", result.getEntityCount()); // total键
		map.put("rows", result.getEntities()); // rows键 存放每页记录 list
		return map;
	}

	/**
	 * 获取平台通用代码信息
	 *
	 * @author 朱锋
	 * @param response
	 * @param request
	 * @return ModelAndView
	 * @throws Exception
	 *             ModelAndView
	 */
	@RequestMapping(value = "/getCommTempletSysCodeData")
	public Map<String,Object> getCommTempletSysCodeData(HttpServletResponse response, HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		Map<String, Object> parameter = new HashMap<String, Object>();
		Paging<CbbTempletCode> page = new Paging<CbbTempletCode>();
		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		String sysId = request.getParameter("sysId");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		String codeType = request.getParameter("codeType");
		String codeName = request.getParameter("codeName");
		parameter.put("codeType", codeType);
		parameter.put("codeName", codeName);
		sysId = "LANTOP";
		page.setPageSize(ComUtil.getPageSize(pageSize));
		page.setPageNo(ComUtil.getPageNo(pageNo));
		Page<Map<String, Object>> result = commTempletManagerService.getPageSysCodeDetailList(page, parameter, sysId);
		map.put("total", result.getEntityCount()); // total键
		map.put("rows", result.getEntities()); // rows键 存放每页记录 list
		return map;
	}

	/**
	 * 获取生成方式
	 *
	 * @author 朱锋
	 * @param response
	 * @param request
	 * @return ModelAndView
	 * @throws Exception
	 *             ModelAndView
	 */
	@RequestMapping(value = "/getCommTempletRuleData")
	@ResponseBody
	public Map<String,Object> getCommTempletRuleData(HttpServletResponse response, HttpServletRequest request) throws Exception {
		Map<String,Object> mav = new HashMap<>();
		Map<String, Object> parameter = new HashMap<String, Object>();
		Paging<CbbTempletCode> page = new Paging<CbbTempletCode>();
		String pageNo = ServletRequestUtils.getStringParameter(request,"page","");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		page.setPageSize(ComUtil.getPageSize(pageSize));
		page.setPageNo(ComUtil.getPageNo(pageNo));
		Page<Map<String, Object>> result = commTempletManagerService.getPageRuleDetailList(page, parameter);
		mav.put("total", result.getEntityCount()); // total键
		mav.put("rows", result.getEntities()); // rows键 存放每页记录 list
		return mav;
	}

	/**
	 * 获取平台通用代码子信息
	 *
	 * @author 朱锋
	 * @param response
	 * @param request
	 * @return ModelAndView
	 * @throws Exception
	 *             ModelAndView
	 */
	@RequestMapping(value = "/getCommTempletSysCodeSonData")
	@ResponseBody
	public Map<String,Object> getCommTempletSysCodeSonData(HttpServletResponse response, HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String cid = ServletRequestUtils.getStringParameter(request,"cid","");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("cid", cid);
		Paging<CbbTempletCode> page = new Paging<CbbTempletCode>();
		String pageNo = request.getParameter("page");// 取得当前页码
		String pageSize = request.getParameter("rows");// 取得一页显示的数量
		page.setPageSize(ComUtil.getPageSize(pageSize));
		page.setPageNo(ComUtil.getPageNo(pageNo));
		Page<Map<String, Object>> result = commTempletManagerService.getPageSysCodeSonList(page, parameter, sysId);
		map.put("total", result.getEntityCount()); // total键
		map.put("rows", result.getEntities()); // rows键 存放每页记录 list
		return map;
	}

	/**
	 * 系统通用代码选择页面
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/toCommTempletScodeAdd")
	public ModelAndView toCommTempletScodeAdd(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String dialogId = ServletRequestUtils.getStringParameter(request,"dialogId","");
		String tId = ServletRequestUtils.getStringParameter(request,"tId","");
		String fId = ServletRequestUtils.getStringParameter(request,"fid","");
		String flag = ServletRequestUtils.getStringParameter(request,"flag","");
		mav.addObject("dialogId", dialogId);
		mav.addObject("tId", tId);
		mav.addObject("fId", fId);
		mav.addObject("flag", flag);
		mav.setViewName("avicit/cbb/techclass/tabledefine/commtempletmanager/comm_sys_code_manager");
		return mav;
	}

	/**
	 * 初始化字段维护界面
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/toInitFieldConfig")
	public ModelAndView toInitFieldConfig(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String dialogId = ServletRequestUtils.getStringParameter(request,"dialogId","");
		String tId = ServletRequestUtils.getStringParameter(request,"tId","");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		mav.addObject("dialogId", dialogId);
		mav.addObject("sysId", sysId);
		mav.addObject("tId", tId);
		mav.setViewName("avicit/cbb/techclass/tabledefine/commtempletmanager/comm_init_field_manager");
		return mav;
	}

	/**
	 * 参考模板字段信息名称唯一性验证
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/checkFieldUnique")
	@ResponseBody
	public Map<String,Object> checkFieldUnique(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String json = request.getParameter("param");
		String sysId = request.getParameter("sysId");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		CbbTempletField commTempletField = JsonHelper.getInstance().readValue(json, CbbTempletField.class);
		try {
			// 唯一性验证【名称唯一性验证】
			boolean codeUnique = false;
			String id = commTempletField.getId();
			String name = commTempletField.getColName();
			String tId = commTempletField.getTempletId();
			codeUnique = commTempletManagerService.checkFieldUnique(name, tId, id, sysId);
			if (codeUnique) {
				map.put("flag", "字段名<font color='blue'>[" + name + "]</font>已存在,请重新填写!");
			} else {
				map.put("flag", OpResult.success);
			}
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}

		return map;
	}

	/**
	 * 参考模板字段信息保存方法
	 *
	 * @param request
	 *            请求参数
	 * @return
	 */
	@RequestMapping(value = "/insertOrUpdateCommTempletField")
	@ResponseBody
	public Map<String,Object> doDetailSave(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String json = request.getParameter("param");
		String sysId = request.getParameter("sysId");
		sysId = "LANTOP";
		CbbTempletField commTempletField = JsonHelper.getInstance().readValue(json, CbbTempletField.class);
		boolean isUpdate = StringUtils.isBlank(commTempletField.getId()) ? false : true;
		try {
			if (isUpdate) {
				commTempletManagerService.updateDetailCommTempletField(commTempletField, sysId);
			} else {
				commTempletManagerService.insertCommTempletField(commTempletField, sysId, ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId());
			}
			map.put("flag", OpResult.success);
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}
		return map;
	}

	/**
	 * 初始化字段保存方法（新增，更新）
	 *
	 * @author 朱锋
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/saveCbbTempletFieldInItData")
	@ResponseBody
	public Map<String,Object> saveCbbTempletFieldInItData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String insertData = ServletRequestUtils.getStringParameter(request,"insertData","");
		String updateData = ServletRequestUtils.getStringParameter(request,"updateData","");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		sysId = "LANTOP";
		String templetId = ServletRequestUtils.getStringParameter(request,"templetId","");
		try {
			// 更新
			if (!"".equals(updateData) && !"[]".equals(updateData)) {
				CbbTempletField[] ccArray = JsonUtils.newInstance().Json2BeanArray(updateData, CbbTempletField.class);// 实体类列对象数组
				commTempletManagerService.updateCbbTempletFieldArray(ccArray, templetId, sysId);
			}
			// 新增
			if (!"".equals(insertData) && !"[]".equals(insertData)) {
				CbbTempletField[] ccArray = JsonUtils.newInstance().Json2BeanArray(insertData, CbbTempletField.class);// 实体类列对象数组
				commTempletManagerService.insertCbbTempletFieldArray(ccArray, sysId, ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(), templetId);
			}
			map.put("flag", OpResult.success);
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
			map.put("mes", e.getMessage());
			e.printStackTrace();
		}

		return map;
	}

	/***
	 * 保存CbbTempletField数据
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/insertOrUpdateCommTempletFieldAll")
	@ResponseBody
	public Map<String,Object> saveCommTempletFieldData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		// 获取 新增，更新 数据
		String insertData = ServletRequestUtils.getStringParameter(request, "insertData", "");
		String updateData = ServletRequestUtils.getStringParameter(request, "updateData", "");
		String templetId = ServletRequestUtils.getStringParameter(request, "templetId", "");
		String templetModelType = this.getTempletModelTypeById(templetId);
		String templetIdPid = this.getTempletPidById(templetId);
		String orgId = ThreadContextHelper.getOrgId();

		String sysId = request.getParameter("sysId");
		sysId = "LANTOP";
		try {
			if (!updateData.equals("") && !updateData.equals("[]")) {
				// 将数据转换成CommTempletField对象
				CbbTempletField[] cbbTempltFields = JsonUtils.newInstance().Json2BeanArray(updateData, CbbTempletField.class);
				/*
				 * // 循环，判断唯一性，添加数据 boolean isUnique = false; // 字段名唯一性标识 boolean labelUnique = false; // 字段中文名唯一性标识 for (int i = 0; i < cbbTempltFields.length; i++) { // 设置属性
				 * CbbTempletField cbbTempltField = cbbTempltFields[i]; // 调用方法验证唯一性 String name = cbbTempltField.getColName(); String label = cbbTempltField.getColLabel(); String
				 * id = cbbTempltField.getId(); isUnique = commTempletManagerService.checkFieldUnique(name, templetId, id, sysId); if (isUnique) { // 存在重复数据 mav.addObject("flag",
				 * OpResult.failure); mav.addObject("mes", "字段名<font color='blue'>[" + name + "]</font>已存在,请重新填写!"); // 跳出for循环 break; } if (labelUnique) { // 存在重复数据
				 * mav.addObject("flag", OpResult.failure); mav.addObject("mes", "字段中文名<font color='blue'>[" + label + "]</font>已存在,请重新填写!"); // 跳出for循环 break; } }
				 */
				// 数据没有重复,调用添加方法
				/*
				 * if (false == isUnique && false == labelUnique) { }
				 */
				/*Map<String, String> map = this.opinionNewFieldNameRepetition(cbbTempltFields, templetIdPid, orgId, templetModelType);
				if (map.get("1").equals("yes")) {

					mav.addObject("flag", OpResult.success);
				} else {
					mav.addObject("flag", OpResult.failure);
					mav.addObject("mes", "字段" + map.get("2") + "已存在，请检查！");
				}*/
				commTempletManagerService.updateDetailCommTempletFields(cbbTempltFields, sysId);
			}
			if (!insertData.equals("") && !insertData.equals("[]")) {
				// 存在新增数据
				// 将数据转换成CommTempletField对象数组
				CbbTempletField[] cbbTempltFields = JsonUtils.newInstance().Json2BeanArray(insertData, CbbTempletField.class);
				/*
				 * boolean isUnique = false; // 字段名唯一性标识 boolean labelUnique = false; // 字段中文名唯一性标识 for (int i = 0; i < cbbTempltFields.length; i++) { CbbTempletField
				 * cbbTempltField = cbbTempltFields[i]; // 调用方法验证唯一性 String name = cbbTempltField.getColName(); String label = cbbTempltField.getColLabel(); String id =
				 * cbbTempltField.getId(); isUnique = commTempletManagerService.checkFieldUnique(name, templetId, id, sysId); labelUnique = commTempletManagerService
				 * .checkFieldLabelUnique(label, templetId, id, sysId); if (isUnique) { // 存在重复数据 mav.addObject("flag", OpResult.failure); mav.addObject("mes",
				 * "字段名<font color='blue'>[" + name + "]</font>已存在,请重新填写!"); // 跳出for循环 break; } if (labelUnique) { // 字段中文名重复 mav.addObject("flag", OpResult.failure);
				 * mav.addObject("mes", "字段中文名<font color='blue'>[" + label + "]</font>已存在,请重新填写!"); // 跳出for循环 break; } }
				 */
				// 数据没有重复,调用添加方法
				/*
				 * if (false == isUnique && false == labelUnique) { }
				 */
				/*Map<String, String> map = this.opinionNewFieldNameRepetition(cbbTempltFields, templetIdPid, orgId, templetModelType);
				if (map.get("1").equals("yes")) {
					mav.addObject("flag", OpResult.success);
				} else {
					mav.addObject("flag", OpResult.failure);
					mav.addObject("mes", "字段" + map.get("2") + "已存在，请检查！");
				}*/
				commTempletManagerService.insertCommTempletFields(cbbTempltFields, sysId, ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(), templetId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("flag", OpResult.failure);
			map.put("mes", e.getMessage());
		}
		return map;
	}

	/**
	 * 根据模板id查询初始化字段pid
	 * @return templetId
	 */
	private String getTempletPidById(String templetId) {
		String templetPid = "";
		CbbTempletInfo c = null;
		String tempType = "C";
		while (!tempType.equals("S")) {
			c = commTempletManagerService.getCommTempletInfoById(templetId);
			templetId = c.getParentId();
			tempType = c.getTempType();
		}
		templetPid = c.getId();
		return templetPid;
	}

	/**
	 * 根据模板id查询模板类型
	 * @return templetId
	 */
	private String getTempletModelTypeById(String templetId) {
		CbbTempletInfo c = null;
		c = commTempletManagerService.getCommTempletInfoById(templetId);
		return c.getTempModelType();
	}

	/**
	 * 判断新添加字段名是否和初始化字段名重复
	 * @return templetId,cbbTempltFields,orgId
	 */
	private Map<String, String> opinionNewFieldNameRepetition(CbbTempletField[] cbbTempltFields, String templetId, String orgId, String templetModelType) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("1", "yes");
		List<Map<String, Object>> list = commTempletManagerService.getCommTempletFieldByTempletId(orgId, templetModelType, templetId);
		if (list.size() > 0) {
			for (CbbTempletField ctf : cbbTempltFields) {
				String filedName = ctf.getColName();
				for (int i = 0; i < list.size(); i++) {
					String tempFiledName = list.get(i).get("COL_NAME").toString();
					if (filedName.equals(tempFiledName)) {
						map.put("1", "no");
						map.put("2", filedName);
						break;
					}
				}
			}
		}
		return map;
	}

	/***
	 * 初始化字段维护 保存CbbTempletField数据
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/insertOrUpdateCommTempletInitFieldAll")
	@ResponseBody
	public Map<String,Object> saveCommTempletInitFieldData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		// 获取 新增，更新 数据
		String insertData = request.getParameter("insertData");
		String updateData = request.getParameter("updateData");
		String templetId = request.getParameter("templetId");
		String sysId = request.getParameter("sysId");
		sysId = "LANTOP";
		try {
			if (!insertData.equals("") && !insertData.equals("[]")) {
				// 存在新增数据
				// 将数据转换成CommTempletField对象数组
				CbbTempletField[] cbbTempltFields = JsonUtils.newInstance().Json2BeanArray(insertData, CbbTempletField.class);
				// 重复数据标示
				boolean isUnique = false;
				for (int i = 0; i < cbbTempltFields.length; i++) {
					CbbTempletField cbbTempltField = cbbTempltFields[i];
					// 调用方法验证唯一性
					String name = cbbTempltField.getColName();
					String id = cbbTempltField.getId();
					isUnique = commTempletManagerService.checkFieldUnique(name, templetId, id, sysId);
					if (isUnique) {
						// 存在重复数据
						map.put("flag", OpResult.failure);
						map.put("mes", "字段名<font color='blue'>[" + name + "]</font>已存在,请重新填写!");
						// 跳出for循环
						break;
					}
				}
				// 数据没有重复,调用添加方法
				if (!isUnique) {
					commTempletManagerService.insertCommTempletInitFields(cbbTempltFields, sysId, ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(), templetId);
					map.put("flag", OpResult.success);
				}
			}
			if (!updateData.equals("") && !updateData.equals("[]")) {
				// 将数据转换成CommTempletField对象
				CbbTempletField[] cbbTempltFields = JsonUtils.newInstance().Json2BeanArray(updateData, CbbTempletField.class);
				// 循环，判断唯一性，添加数据
				// 重复数据标示
				boolean isUnique = false;
				for (int i = 0; i < cbbTempltFields.length; i++) {
					// 设置属性
					CbbTempletField cbbTempltField = cbbTempltFields[i];
					// 调用方法验证唯一性
					String name = cbbTempltField.getColName();
					String id = cbbTempltField.getId();
					isUnique = commTempletManagerService.checkFieldUnique(name, templetId, id, sysId);
					if (isUnique) {
						// 存在重复数据
						map.put("flag", OpResult.failure);
						map.put("mes", "字段名<font color='blue'>[" + name + "]</font>已存在,请重新填写!");
						// 跳出for循环
						break;
					}
				}
				// 数据没有重复,调用添加方法
				if (!isUnique) {
					commTempletManagerService.updateDetailCommTempletFields(cbbTempltFields, sysId);
					map.put("flag", OpResult.success);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("flag", OpResult.failure);
			map.put("mes", e.getMessage());
		}
		return map;
	}

	/**
	 * 手写通用代码保存方法
	 *
	 * @param request
	 *            请求参数
	 * @return
	 */
	@RequestMapping(value = "/saveTempletFieldCodeData")
	@ResponseBody
	public Map<String,Object> saveTempletFieldCodeData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String inserCodeData = ServletRequestUtils.getStringParameter(request, "inserCodeData", "");
		String updateCodeData = ServletRequestUtils.getStringParameter(request, "updateCodeData", "");
		String templetId = ServletRequestUtils.getStringParameter(request, "templetId", "");
		String fieldId = ServletRequestUtils.getStringParameter(request, "fieldId", "");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		try {
			// 更新
			if (!"".equals(updateCodeData) && !"[]".equals(updateCodeData)) {
				commTempletManagerService.updateCbbTempletFieldCodeArray(updateCodeData, templetId, fieldId, sysId);
			}
			// 新增
			if (!"".equals(inserCodeData) && !"[]".equals(inserCodeData)) {
				commTempletManagerService.insertCbbTempletFieldCodeArray(inserCodeData, sysId, ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(), templetId, fieldId);
			}
			map.put("flag", OpResult.success);
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
			map.put("mes", e.getMessage());
		}

		return map;
	}

	/**
	 * 根据中文标题转换为英文标题
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/onChangeCol")
	@ResponseBody
	public Map<String,Object> onChangeCol(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<>();
		String name = ServletRequestUtils.getStringParameter(request,"name","");
		String textpinyin = Pinyin4jUtil.getPinYinHeadChar(name).toUpperCase();// 根据分类树名称转换为拼音首字母
		map.put("textpinyin", textpinyin);
		return map;
	}

	/**
	 * 参考模板字段信息跳转编辑取值
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toCommTempletFieldEdit")
	public ModelAndView toCommTempletFieldEdit(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		String id = request.getParameter("id");
		String dialogId = request.getParameter("dialogId");
		String toJspUrl = request.getParameter("toJspUrl");
		String flag = request.getParameter("flag");
		String sysId = request.getParameter("sysId");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		CbbTempletField commTempletField = commTempletManagerService.getCommTempletFieldById(id);
		mav.addObject("commTempletField", commTempletField);
		mav.addObject("dialogId", dialogId);
		mav.addObject("flag", flag);
		mav.setViewName(toJspUrl);
		return mav;
	}

	/**
	 * 参考模板代码维护跳转编辑取值
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toCommTempletCodeEdit")
	public ModelAndView toCommTempletCodeEdit(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		String id = request.getParameter("id");
		String dialogId = request.getParameter("dialogId");
		String toJspUrl = request.getParameter("toJspUrl");
		String flag = request.getParameter("flag");
		String sysId = request.getParameter("sysId");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		CbbTempletCode commTempletCode = commTempletManagerService.getCommTempletCodeById(id);
		mav.addObject("commTempletCode", commTempletCode);
		mav.addObject("dialogId", dialogId);
		mav.addObject("flag", flag);
		mav.setViewName(toJspUrl);
		return mav;
	}

	/**
	 * 删除参考模板字段信息操作
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/deleteCommTempletField")
	@ResponseBody
	public Map<String,Object> deleteCommTempletField(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<>();
		try {
			String ids = ServletRequestUtils.getStringParameter(request, "ids", "");
			String sysId = ServletRequestUtils.getStringParameter(request, "sysId", "");
			if ("".equals(sysId) || sysId == null) {
				sysId = "CBB";
			}
			sysId = "LANTOP";
			if (ids != null && !"".equals(ids)) {
				commTempletManagerService.deleteCommTempletField(ids, sysId);
				map.put("flag", OpResult.success);
			}
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}

		return map;
	}

	/**
	 * 删除参考模板代码维护信息操作
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/deleteCommTempletCode")
	@ResponseBody
	public Map<String,Object> deleteCommTempletCode(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<>();
		try {
			String deleteData = request.getParameter("deleteData");
			String templetId = request.getParameter("templetId");
			String fieldId = request.getParameter("fieldId");
			String sysId = request.getParameter("sysId");
			if ("".equals(sysId) || sysId == null) {
				sysId = "CBB";
			}
			sysId = "LANTOP";
			commTempletManagerService.deletecommTempletCodeBydeleteData(deleteData, templetId, fieldId, sysId);
			map.put("flag", OpResult.success);
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}
		return map;
	}

	/**
	 * 此方法描述的是:分类树加载
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author zhuf
	 * @createDate 2014-8-21
	 * @version 1.0
	 */
	@RequestMapping("/findChildsNode")
	@ResponseBody
	public Map<String,Object> findChildsNode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String parentId = ServletRequestUtils.getStringParameter(request,"parentId","");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		String id = parentId;
		try {
			int count = commTempletManagerService.getParentNodeByParentId("ROOT");
			if (count == 0) {
				// 获取顶层节点
				String deptId = (String) request.getSession().getAttribute("deptId");
				commTempletManagerService.saveRootLantopArchiveTabClassVByType(deptId);
			}
			// 默认为根节点
			id = "ROOT";
			// 根据orgId过滤过滤树节点 - 2015/12/11 - update
			nodes = commTempletManagerService.getCommTempletInfoTreeNodes(id, sysId, ThreadContextHelper.getOrgId());
			map.put("result", OpResult.success.ordinal());
		} catch (Exception e) {
			map.put("result", OpResult.failure.ordinal());
			map.put("msg", "后台处理异常，" + e.getMessage());
		}
		map.put("data", nodes);
		return map;
	}

	/**
	 * 此方法描述的是:总组织分类树加载
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author zhuf
	 * @createDate 2014-8-21
	 * @version 1.0
	 */
	@RequestMapping("/findChildsNodeRoot")
	@ResponseBody
	public Map<String,Object> findChildsNodeRoot(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String parentId = ServletRequestUtils.getStringParameter(request,"parentId","");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId");
		if ("".equals(sysId) || sysId == null) {
			sysId = "CBB";
		}
		sysId = "LANTOP";
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		String id = parentId;
		try {
			int count = commTempletManagerService.getParentNodeByParentId("ROOT");
			if (count == 0) {
				// 获取顶层节点
				String deptId = (String) request.getSession().getAttribute("deptId");
				commTempletManagerService.saveRootLantopArchiveTabClassVByType(deptId);
			}
			// 默认为根节点
			id = "ROOT";
			// 根据orgId过滤过滤树节点 - 2015/12/11 - update
			nodes = commTempletManagerService.getCommTempletInfoTreeNodesRoot(id, sysId, "ORG_ROOT");// 总组织默认根节点ID是ORG_ROOT
			map.put("result", OpResult.success.ordinal());
		} catch (Exception e) {
			map.put("result", OpResult.failure.ordinal());
			map.put("msg", "后台处理异常，" + e.getMessage());
		}
		map.put("data", nodes);
		return map;
	}




	/**
	 * 获取列最大排序值
	 *
	 * @author 朱锋
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/getColMaxOrder")
	@ResponseBody
	public Map<String,Object> getColMaxOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String sysId = ServletRequestUtils.getStringParameter(request, "sysId", "");
		sysId = "LANTOP";
		String templetId = ServletRequestUtils.getStringParameter(request, "templetId", "");
		// 判断该表是否有值
		int num = commTempletManagerService.getMaxOrderNum(templetId,sysId);
		map.put("num", num);
		return map;
	}

	/**
	 * 导出结构模板
	 *
	 * @author 朱锋
	 * @param request
	 * @param response
	 * @throws Exception
	 *             void
	 * @throws
	 */
	@RequestMapping("/exportExcelMoudle")
	public void exportExcelMoudle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		// 创建表头值List
		List<String> headValue = new ArrayList<String>();
		headValue.add("字段中文名");
		headValue.add("字段名");
		headValue.add("字段类型");
		headValue.add("长度");
		headValue.add("小数位数");
		headValue.add("是否可见");
		headValue.add("是否必著");
		headValue.add("是否显示");
		headValue.add("是否编辑");
		headValue.add("是否列表显示");
		headValue.add("是否详细显示");
		headValue.add("查询字段");
		headValue.add("下拉类型");
		headValue.add("顺序");
		headValue.add("备注");
		try {
			// 导出excel
			commTempletManagerService.exportExcelModule(headValue, os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 设置response参数，可以打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(("参考模板字段信息模板.xls").getBytes("GBK"), "iso8859-1"));
			response.setHeader("Content-length", String.valueOf(content.length));
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead = 0;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bos.flush();
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (bis != null) {
				bis.close();
			}
			if (bos != null) {
				bos.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 导出结构数据
	 *
	 * @author 朱锋
	 * @param request
	 * @param response
	 * @throws Exception
	 *             void
	 * @throws
	 */
	@RequestMapping("/exportData")
	public void exportData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 填充projects数据
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		// 获取参数
		String templetId = request.getParameter("templetId");
		try {
			// 获取数据
			List<Map<String, Object>> datas = commTempletManagerService.getCbbTempletFields(templetId, ThreadContextHelper.getOrgId());
			// 按照页面数据字段展示顺序构造excel文件标题行集合
			List<String> head = new ArrayList<String>();
			head.add("COL_LABEL");
			head.add("COL_NAME");
			head.add("COL_TYPE");
			head.add("COL_LENGTH");
			head.add("COL_DECIMAL");
			head.add("COL_IS_DISPLAY");
			head.add("COL_IS_MUST");
			head.add("COL_IS_VISIBLE");
			head.add("COL_IS_EDIT");
			head.add("COL_IS_TAB_VISIBLE");
			head.add("COL_IS_DETAIL");
			head.add("COL_IS_SEARCH");
			head.add("COL_DROPDOWN_TYPE");
			head.add("COL_ORDER");
			head.add("REMARK");
			// 创建表头值List
			List<String> headValue = new ArrayList<String>();
			headValue.add("字段中文名");
			headValue.add("字段名");
			headValue.add("字段类型");
			headValue.add("长度");
			headValue.add("小数位数");
			headValue.add("是否可见");
			headValue.add("是否必著");
			headValue.add("是否显示");
			headValue.add("是否编辑");
			headValue.add("是否列表显示");
			headValue.add("是否详细显示");
			headValue.add("查询字段");
			headValue.add("下拉类型");
			headValue.add("顺序");
			headValue.add("备注");
			// 导出excel
			commTempletManagerService.exportData(headValue, head, datas, os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 构造文件名
			String fileName = commTempletManagerService.getFileName(templetId);
			// 设置response参数，可以打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes("GBK"), "iso8859-1"));
			response.setHeader("Content-length", String.valueOf(content.length));
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead = 0;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bos.flush();
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (bis != null) {
				bis.close();
			}
			if (bos != null) {
				bos.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 导入excel文件
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/importData")
	public ModelAndView importData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView("");
		// 获取参数
		String sysId = request.getParameter("sysId");
		sysId = "LANTOP";
		String templetId = request.getParameter("templetId");
		String dialogId = request.getParameter("dialogId");
		mav.addObject("dialogId", dialogId);
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
		// String logoPathDir = "files/commTempletImportFiles";
		/** 得到文件保存目录的真实路径 **/
		String logoRealPathDir = mulRequest.getSession().getServletContext().getRealPath("/");
		if (!logoRealPathDir.endsWith(File.separator)) {
			logoRealPathDir = logoRealPathDir + File.separator;
		}
		logoRealPathDir = logoRealPathDir + "files";
		/** 根据真实路径创建目录 **/
		File logoSaveFile = new File(logoRealPathDir);
		if (!logoSaveFile.exists()) {
			logoSaveFile.mkdirs();
		}
		/** 页面控件的文件流 **/
		MultipartFile multipartFile = mulRequest.getFile("file");
		String fileName = multipartFile.getOriginalFilename();
		/** 拼成完整的文件保存路径加文件 **/
		String filePath = logoRealPathDir + File.separator + SessionHelper.getLoginSysUserId(request) + "_" + System.currentTimeMillis() + "_" + fileName;
		File file = new File(filePath);
		/** 解析Excel数据 **/
		Map<String, Vector<Vector<String>>> excelData = null; // 解析文件后数据
		try {
			// 判断文件类型，调用方法解析excel文件
			if (filePath.endsWith(".xls")) {
				// 解析2003excel文件
				multipartFile.transferTo(file);
				excelData = commTempletManagerService.readXls(filePath);
			} else {
				// 解析2007excel文件
				multipartFile.transferTo(file);
				excelData = commTempletManagerService.readXlsx(filePath);
			}
			mav.addObject("sysId", sysId);
			mav.setViewName("avicit/cbb/techclass/tabledefine/commtempletmanager/table_templet_field_import");
			if (!excelData.isEmpty()) {
				if (excelData.containsKey("sheetNames")) {
					Vector<String> vector = excelData.get("sheetNames").get(0);
					for (int i = 0; i < vector.size(); i++) {
						// 获取表名
						String sheetName = vector.get(i);
						// 根据表名获取表中的数据集合
						Vector<Vector<String>> datas = excelData.get(sheetName);
						// 调用方法验证数据
						commTempletManagerService.testExcel(datas, templetId);
						// 调用方法添加
						commTempletManagerService.insertFromExcel(datas, sysId, SessionHelper.getCurrentOrgId(request), SessionHelper.getCurrentDeptId(request), templetId);
					}
				}
			}
			request.setAttribute("message", "导入成功！");
		} catch (Exception e) {
			request.setAttribute("message", e.getMessage());
			e.printStackTrace();
		} finally {
			// 导入完成删除该文件
			file.delete();
		}
		return mav;
	}

	/**
	 * 初始化字段维护 导出结构模板
	 *
	 * @author 朱锋
	 * @param request
	 * @param response
	 * @throws Exception
	 *             void
	 * @throws
	 */
	@RequestMapping("/initFieldExportExcelMoudle")
	public void initFieldExportExcelMoudle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		// 创建表头值List
		List<String> headValue = new ArrayList<String>();
		headValue.add("字段中文名");
		headValue.add("字段名");
		headValue.add("字段类型");
		headValue.add("长度");
		headValue.add("小数位数");
		headValue.add("是否可见");
		headValue.add("是否必著");
		headValue.add("是否显示");
		headValue.add("是否编辑");
		headValue.add("是否列表显示");
		headValue.add("是否详细显示");
		headValue.add("查询字段");
		headValue.add("下拉类型");
		headValue.add("顺序");
		headValue.add("备注");
		try {
			// 导出excel
			commTempletManagerService.exportExcelModule(headValue, os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 设置response参数，可以打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(("参考模板初始化字段维护模板.xls").getBytes("GBK"), "iso8859-1"));
			response.setHeader("Content-length", String.valueOf(content.length));
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead = 0;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bos.flush();
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (bis != null) {
				bis.close();
			}
			if (bos != null) {
				bos.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 初始化字段维护 导出结构数据
	 *
	 * @author 朱锋
	 * @param request
	 * @param response
	 * @throws Exception
	 *             void
	 * @throws
	 */
	@RequestMapping("/inintFieldExportData")
	public void inintFieldExportData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 填充projects数据
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		// 获取参数
		String templetId = request.getParameter("templetId");
		try {
			// 获取数据
			List<Map<String, Object>> datas = commTempletManagerService.getCbbTempletFields(templetId, SessionHelper.getCurrentOrgId(request));
			// 按照页面数据字段展示顺序构造excel文件标题行集合
			List<String> head = new ArrayList<String>();
			head.add("COL_LABEL");
			head.add("COL_NAME");
			head.add("COL_TYPE");
			head.add("COL_LENGTH");
			head.add("COL_DECIMAL");
			head.add("COL_IS_DISPLAY");
			head.add("COL_IS_MUST");
			head.add("COL_IS_VISIBLE");
			head.add("COL_IS_EDIT");
			head.add("COL_IS_TAB_VISIBLE");
			head.add("COL_IS_DETAIL");
			head.add("COL_IS_SEARCH");
			head.add("COL_DROPDOWN_TYPE");
			head.add("COL_ORDER");
			head.add("REMARK");
			// 创建表头值List
			List<String> headValue = new ArrayList<String>();
			headValue.add("字段中文名");
			headValue.add("字段名");
			headValue.add("字段类型");
			headValue.add("长度");
			headValue.add("小数位数");
			headValue.add("是否可见");
			headValue.add("是否必著");
			headValue.add("是否显示");
			headValue.add("是否编辑");
			headValue.add("是否列表显示");
			headValue.add("是否详细显示");
			headValue.add("查询字段");
			headValue.add("下拉类型");
			headValue.add("顺序");
			headValue.add("备注");
			// 导出excel
			commTempletManagerService.exportData(headValue, head, datas, os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 构造文件名
			String fileName = commTempletManagerService.getFileName(templetId);
			// 设置response参数，可以打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + "初始化字段维护.xls").getBytes("GBK"), "iso8859-1"));
			response.setHeader("Content-length", String.valueOf(content.length));
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead = 0;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bos.flush();
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (bis != null) {
				bis.close();
			}
			if (bos != null) {
				bos.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 初始化字段 导入excel文件
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/initFieldImportData")
	public ModelAndView initFieldImportData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView("");
		// 获取参数
		String sysId = request.getParameter("sysId");
		sysId = "LANTOP";
		String templetId = request.getParameter("templetId");
		String dialogId = request.getParameter("dialogId");
		mav.addObject("dialogId", dialogId);
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
		// String logoPathDir = "files/structureImportFiles";
		/** 得到文件保存目录的真实路径 **/
		String logoRealPathDir = mulRequest.getSession().getServletContext().getRealPath("/");
		if (!logoRealPathDir.endsWith(File.separator)) {
			logoRealPathDir = logoRealPathDir + File.separator;
		}
		logoRealPathDir = logoRealPathDir + "files";
		/** 根据真实路径创建目录 **/
		File logoSaveFile = new File(logoRealPathDir);
		if (!logoSaveFile.exists()) {
			logoSaveFile.mkdirs();
		}
		/** 页面控件的文件流 **/
		MultipartFile multipartFile = mulRequest.getFile("file");
		String fileName = multipartFile.getOriginalFilename();
		/** 拼成完整的文件保存路径加文件 **/
		String filePath = logoRealPathDir + File.separator + SessionHelper.getLoginSysUserId(request) + "_" + System.currentTimeMillis() + "_" + fileName;
		File file = new File(filePath);
		/** 解析Excel数据 **/
		Map<String, Vector<Vector<String>>> excelData = null; // 解析文件后数据
		try {
			// 判断文件类型，调用方法解析excel文件
			if (filePath.endsWith(".xls")) {
				// 解析2003excel文件
				multipartFile.transferTo(file);
				excelData = commTempletManagerService.readXls(filePath);
			} else {
				// 解析2007excel文件
				multipartFile.transferTo(file);
				excelData = commTempletManagerService.readXlsx(filePath);
			}
			mav.addObject("sysId", sysId);
			mav.setViewName("avicit/cbb/techclass/tabledefine/commtempletmanager/comm_init_field_import");
			if (!excelData.isEmpty()) {
				if (excelData.containsKey("sheetNames")) {
					Vector<String> vector = excelData.get("sheetNames").get(0);
					for (int i = 0; i < vector.size(); i++) {
						// 获取表名
						String sheetName = vector.get(i);
						// 根据表名获取表中的数据集合
						Vector<Vector<String>> datas = excelData.get(sheetName);
						// 调用方法验证数据
						commTempletManagerService.initFieldTestExcel(datas, templetId);
						// 调用方法添加
						commTempletManagerService.initFieldInsertFromExcel(datas, sysId, SessionHelper.getCurrentOrgId(request), SessionHelper.getCurrentDeptId(request), templetId);
					}
				}
			}
			request.setAttribute("message", "导入成功！");
		} catch (Exception e) {
			request.setAttribute("message", e.getMessage());
			e.printStackTrace();
		} finally {
			// 导入完成删除该文件
			file.delete();
		}
		return mav;
	}

	/**
	 * 初始化字段同步业务表
	 *
	 * @author 朱锋
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/sameCbbTabColumnsData")
	@ResponseBody
	public Map<String,Object> sameCbbTabColumnsData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		sysId = "LANTOP";
		try {
			commTableManagerService.sameCbbTabColumnsData(sysId, ThreadContextHelper.getOrgId()
					, ThreadContextHelper.getDeptId(), SessionHelper.getLoginSysUserId(request), RequestUtil.getClientIp(request));
			map.put("flag", OpResult.success);
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
			map.put("mes", e.getMessage());
			e.printStackTrace();
		}

		return map;
	}

	/**
	 * 参考模板字段信息查询页面
	 * @author 朱锋
	 * @param request
	 * @return ModelAndView
	 * @throws
	 */
	@RequestMapping("/toTempletSearchForm")
	public ModelAndView toTempletSearchForm(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String dialogId = ServletRequestUtils.getStringParameter(request,"dialogId","");
		mav.addObject("dialogId", dialogId);
		mav.setViewName("avicit/cbb/techclass/tabledefine/commtempletmanager/comm_templet_search");
		return mav;
	}

	/**
	 * 参考模板系统代码选择信息查询页面
	 * @author 朱锋
	 * @param request
	 * @return ModelAndView
	 * @throws
	 */
	@RequestMapping("/toTempletSearchSysCodeForm")
	public ModelAndView toTempletSearchSysCodeForm(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String dialogId = request.getParameter("dialogId");
		mav.addObject("dialogId", dialogId);
		mav.setViewName("avicit/cbb/techclass/tabledefine/commtempletmanager/comm_sys_code_search");
		return mav;
	}

	/**
	 * 语言选择页面
	 * @param type
	 * @param pid
	 * @param language
	 * @param appid
	 * @param timestamp
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/chooseLanguage/{pid}/{type}")
	public ModelAndView toChooseLanguage(@PathVariable
	String pid, @PathVariable
	String type, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String url = "";
		if (type.equals("1")) {
			url = "platform/cbbtempletfieldtl/CbbTempletFieldTlController/operation/getAllLanguageById/" + pid;
		} else {
			url = "platform/cbbtempletcodetl/CbbTempletCodeTlController/operation/getAllLanguageById/" + pid;

		}
		request.setAttribute("url", url);
		request.setAttribute("name", "lookupTypeName");// lookupName
		request.setAttribute("display", "列显示名称");
		request.setAttribute("flag", true);
		request.setAttribute("type", type);

		mav.setViewName("avicit/cbb/techclass/tabledefine/commtempletmanager/chooseLanguage");
		return mav;
	}

	/**
	 * @author youyu
	 * 验证给定的字段信息是否存在与初始化字段及根组织对应系统节点、模板类型字段中
	 * @param request
	 * @param ModelAndView
	 * */
	@RequestMapping(value = "/duplicateCheck")
	@ResponseBody
	public Map<String,Object> duplicateCheck(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<>();
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		String sysNodeId = ServletRequestUtils.getStringParameter(request,"sysNodeId","");// 系统节点ID
		String tempModelType = ServletRequestUtils.getStringParameter(request,"tempModelType","");// 模板类型
		String nodeRows = ServletRequestUtils.getStringParameter(request,"nodeRows","");// 当前节点字段信息
		String treeType = ServletRequestUtils.getStringParameter(request,"treeType","");// 是否根组织
		String orgId = ThreadContextHelper.getOrgId();
		String deptId = ThreadContextHelper.getDeptId();

		try {
			String msg = commTempletManagerService.duplicateCheck(sysId, orgId, deptId, sysNodeId, tempModelType, nodeRows, treeType);
			map.put("flag", OpResult.success);
			map.put("msg", msg);
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
			map.put("msg", e.getMessage());
			e.printStackTrace();
		}
		return map;
	}


	/**
	 * 根据参考模板类型信息获得当前组织的参考模板信息和根组织的参考模板信息
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getCommTempletByTempModelType")
	@ResponseBody
	public Map<String,Object> getCommTempletByTempModelType(HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String tempModelType = ServletRequestUtils.getStringParameter(request,"tempModelType","");
		String sysId = ServletRequestUtils.getStringParameter(request,"sysId","");
		String orgId = SessionHelper.getCurrentOrgIdentity(request);
		List<Map<String,Object>> list = commTempletManagerService.getCommTempletByTempModelType(sysId,orgId,tempModelType);
		map.put("commTempletInfos", list);
		return map;
	}


}
